package com.esunrising.esungsc.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

public final class HttpUtil {
    private HttpUtil(){

    }

    public static Optional<HttpServletRequest> getRequest(){
        return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
                .filter(requestAttributes -> requestAttributes instanceof ServletRequestAttributes)
                .map(requestAttributes -> ((ServletRequestAttributes)requestAttributes).getRequest());
    }

    /**
     * 根据request获取ip地址
     */
    public static String getIpAddress(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    /**
     * 往url中置入Query参数
     * @param url 原请求URL
     * @param uriVariables Query参数列表
     * @return 置入Query参数后的请求URL
     */
    public static String putQueryParam(String url, Map<String, ?> uriVariables){
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if(uriVariables != null && !uriVariables.isEmpty()) {
            uriVariables.forEach((key, value) -> builder.queryParamIfPresent(key, Optional.of(value)));
        }
        return builder.toUriString();
    }
}
